package com.whalecloud.chart.util;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @Description 文件工具类
 * @Author MarkAsh
 * @Date 2025/2/22
 **/
@Slf4j
public class FileUtils {

    public static void writeFile(File file, HttpServletResponse response){
        if (file != null && file.exists()) {
            try {
                // 设置响应头
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
                response.setContentLength((int) file.length());

                // 将文件内容写入响应
                java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file);
                java.io.OutputStream outputStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                log.error("写出文件失败：{}", e.getMessage(), e);
            }
        }
    }
}
